#策略：EMA
from CTPTraderType import *
import globalvar
import pandas as pd
global EMA_tj
EMA_tj=0
def OnTick(marketdata, strategyname):
    print('OnTick EMA:'+str(marketdata.contents.InstrumentID, encoding="utf-8"))
    global EMA_tj
    EMA_tj=EMA_tj+1
    if EMA_tj>=60:
        EMA_tj=0
        stock_data = pd.DataFrame(
            columns=['Open', 'High', 'Low', 'Close', 'KlineTime', 'Volume', 'Minutes',
                     'InstrumentID', 'TradingDay'])
        for i in range(600):
            stock_data.loc[i] = [globalvar.md.GetKline(marketdata.contents.InstrumentID, i).contents.Open,
                                 globalvar.md.GetKline(marketdata.contents.InstrumentID, i).contents.High,
                                 globalvar.md.GetKline(marketdata.contents.InstrumentID, i).contents.Low,
                                 globalvar.md.GetKline(marketdata.contents.InstrumentID, i).contents.Close,
                                 globalvar.md.GetKline(marketdata.contents.InstrumentID, i).contents.KlineTime,
                                 globalvar.md.GetKline(marketdata.contents.InstrumentID, i).contents.Volume,
                                 globalvar.md.GetKline(marketdata.contents.InstrumentID, i).contents.Minutes,
                                 str(globalvar.md.GetKline(marketdata.contents.InstrumentID,
                                                                i).contents.InstrumentID,
                                     encoding="utf-8"),
                                 str(globalvar.md.GetKline(marketdata.contents.InstrumentID,
                                                                i).contents.TradingDay,
                                     encoding="utf-8")]
            #print('[' + str(i) + ']数据A:%s' % (stock_data.loc[i]))
            #print('[' + str(i) + ']数据B:%s' % (stock_data.iloc[i]))

        # 将数据按照交易日期从远到近排序
        # stock_data.sort('date', inplace=True)
        # ========== 计算移动平均线
        # 分别计算5日、20日、60日的移动平均线
        ma_list = [5, 20, 60]
        # 计算指数平滑移动平均线EMA
        for ma in ma_list:
            stock_data['EMA_' + str(ma)] = pd.DataFrame.ewm(stock_data['Close'], span=ma).mean()
        # 将数据按照交易日期从近到远排序
        # stock_data.sort_values('TradingDay', ascending=False, inplace=True)
        # ========== 将算好的数据输出到csv文件 - 注意：这里请填写输出文件在您电脑中的路径
        # stock_data.to_csv('sh600000_ma_ema.csv', index=False)

        # 第1行数据
        print('EMA数据:%s' % stock_data.iloc[0])
        # 第1行开盘价
        print('EMA数据:%s' % stock_data.iloc[0]['Open'])
        # 第2行数据
        print('EMA数据:%s' % stock_data.iloc[1])
        # 第2行开盘价
        print('EMA数据:%s' % stock_data.iloc[1]['Open'])
        if (float(stock_data.iloc[0]['EMA_5']) > float(stock_data.iloc[0]['EMA_20'])):
            print('EMA买')
            #用限价单 VN_OPT_LimitPrice 方式报单 。通常用涨停价限价单模拟市价，因为市价指令不支持所有的交易所
            exchangeid = globalvar.dict_exchange[str(marketdata.contents.InstrumentID, encoding="utf-8")].split(',')[0]
            result = globalvar.td.InsertOrder(str(marketdata.contents.InstrumentID, encoding="utf-8"), exchangeid, '0', '1',VN_OPT_LimitPrice , marketdata.contents.LastPrice+10, 1)
            result = result + globalvar.td.InsertOrder(str(marketdata.contents.InstrumentID, encoding="utf-8"), exchangeid, '0', '0',VN_OPT_LimitPrice , marketdata.contents.LastPrice+10, 1)
            if result ==0:
                print('报单成功')
            else:
                print('报单失败')
        else:
            print('EMA卖')
            #用限价单 VN_OPT_LimitPrice 方式报单 。通常用涨停价限价单模拟市价，因为市价指令不支持所有的交易所
            exchangeid = globalvar.dict_exchange[str(marketdata.contents.InstrumentID, encoding="utf-8")].split(',')[0]
            result = globalvar.td.InsertOrder(str(marketdata.contents.InstrumentID, encoding="utf-8"), exchangeid, '1', '1',VN_OPT_LimitPrice , marketdata.contents.LastPrice-10, 1)
            result = result + globalvar.td.InsertOrder(str(marketdata.contents.InstrumentID, encoding="utf-8"), exchangeid,'1', '0',VN_OPT_LimitPrice , marketdata.contents.LastPrice-10, 1)
            if result ==0:
                print('报单成功')
            else:
                print('报单失败')


